package com.adjaisd.scarecrow.service.impl;

import com.adjaisd.scarecrow.entity.User;
import com.adjaisd.scarecrow.mapper.UserMapper;
import com.adjaisd.scarecrow.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author adjaisd
 * @since 2022-03-05
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;

    public boolean existUser(String username, String password) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        List<User> users = userMapper.selectByMap(map);
        return users.size() > 0;
    }

    @Override
    public boolean existUserByUsername(String username) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", username);
        List<User> users = userMapper.selectByMap(map);
        return users.size() > 0;
    }

    @Override
    public boolean existUserByAccount(String account) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("account", account);
        List<User> users = userMapper.selectByMap(map);
        return users.size() > 0;
    }

    @Override
    public User getUserById(long id) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public User getUserByAccount(String account) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public User getUserByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public int addNewUser(User user) {
        userMapper.insert(user);
        User newUser = getUserByUsername(user.getUsername());
        newUser.setAccount("scarecrow" + newUser.getId()); // 更新用户名
        return userMapper.updateById(newUser);
    }

    @Override
    public boolean updateUserinfoById(long userId, String account, String sex, Long birthday, String signature) {
        User user = userMapper.selectById(userId);
        user.setAccount(account);
        int i = userMapper.updateById(user);
        return i > 0;
    }

    @Override
    public boolean updateAvatarById(long userId, String avatar) {
        User user = userMapper.selectById(userId);
        user.setAvatar(avatar);
        int i = userMapper.updateById(user);
        return i > 0;
    }
}
